<!-- 算法配置相关页面 -->
<template>
    <div class="container">
        <div class="header">
            <el-select
            v-model="valueType"
            placeholder="请选择用户类型"
            size="large"
            style="width: 240px"
        >
            <el-option
            v-for="item in formattedOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            />
        </el-select>
        <el-input v-model="inputName" style="width: 240px;height: 2.5rem;margin-left: 2rem;" size="large" placeholder="请输入用户名" />

        <el-button type="primary" style="width: 10rem;height: 2.5rem;margin-left: 2rem;" @click="selectUserByCondition()">查询</el-button>  
       
        <el-button type="primary" style="width: 10rem;height: 2.5rem;margin-left: 2rem;" @click="addAlgorithm()">新建用户</el-button>  
        <!-- 点击新建按钮触发的弹窗 -->
        <el-dialog
             v-model="dialogVisibleAdd"
             title="添加用户"
             width="500" 
        >
        <div style="width: 100%;display: flex;justify-content: space-evenly;">
            <div style="line-height: 2rem;width: 30%;"><span style="color: red;">*</span>用户名：</div>  <el-input v-model="userName" style="width: 70%;height: 2rem;" />
        </div>
        <div style="width: 100%;display: flex;justify-content: space-evenly;margin-top: 1rem;">
            <div style="line-height: 2rem;width: 30%;"><span style="color: red;">*</span>用户类型：</div>      
            <el-select
            v-model="valueAddNew"
            placeholder="请选择用户类型"
            style="width: 70%"
        >
            <el-option
            v-for="item in formattedOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            />
        </el-select>
        </div>   
        <template #footer>
            <div class="dialog-footer">
            <el-button @click="dialogVisibleAdd = false">取消</el-button>
            <el-button type="primary" @click="upLoadMessage">
                确定
            </el-button>
            </div>
        </template>
        </el-dialog>
        </div>


        <!-- 这个是修改用户需要传递的数据 -->
        <el-dialog
             v-model="dialogVisibleChange"
             title="修改用户"
             width="500" 
        >
        <div style="width: 100%;display: flex;justify-content: space-evenly;">
            <div style="line-height: 2rem;width: 30%;"><span style="color: red;">*</span>用户名：</div>  <el-input v-model="userNameChange" style="width: 70%;height: 2rem;" />
        </div>
        <div style="width: 100%;display: flex;justify-content: space-evenly;margin-top: 1rem;">
            <div style="line-height: 2rem;width: 30%;"><span style="color: red;">*</span>用户类型：</div>      
            <el-select
            v-model="valueChange"
            placeholder="请选择用户类型"
            style="width: 70%"
        >
            <el-option
            v-for="item in formattedOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            />
        </el-select>
        </div>
        <div style="width: 100%;display: flex;justify-content: space-evenly;margin-top: 1rem;">
            <div style="line-height: 2rem;width: 30%;"><span style="color: red;">*</span>密码：</div>  <el-input v-model="passwordChange"  type="password" style="width: 70%;height: 2rem;" />
        </div>
        <div style="width: 100%;display: flex;justify-content: space-evenly;margin-top: 1rem;">
            <div style="line-height: 2rem;width: 30%;"><span style="color: red;">*</span>确认密码：</div>  <el-input v-model="passwordConfirm"  type="password" style="width: 70%;height: 2rem;" />
        </div>
        
       
        <template #footer>
            <div class="dialog-footer">
            <el-button @click="dialogVisibleChange = false">取消</el-button>
            <el-button type="primary" @click="upLoadMessage1">
                确定
            </el-button>
            </div>
        </template>
        </el-dialog>


        <div class="main">
          <el-table
          :data="tableData1"
          border
          style="width: 100%; background-color: #fff;"
          highlight-current-row
          :header-cell-style="{ background: '#f5f7fa', color: '#333', fontWeight: 600 }"
          >
  <!-- 序号 -->
  <el-table-column label="序号" width="80">
    <template #default="scope">
      {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
    </template>
  </el-table-column>

  <!-- 用户名 -->
  <el-table-column prop="username" label="用户名" />

  <!-- 用户类型 -->
  <el-table-column prop="roleName" label="用户类型" />

  <!-- 操作 -->
  <el-table-column prop="apiAddress" label="操作" width="200">
    <template #default="scope">
      <div style="display: flex; gap: 8px;">
        <el-button
          link
          type="primary"
          size="small"
          @click="changeAlgorithm(scope.row)"
        >
          修改
        </el-button>
        <el-button
          link
          type="primary"
          size="small"
          style="color: red;"
          @click="deleteItem(scope.row)"
        >
          删除
        </el-button>
      </div>
    </template>
  </el-table-column>
</el-table>

        </div>
        <Pagination
            :total="totalItems"
            :page-size="pageSize"
            v-model:currentPage="currentPage"
             />
    </div>
</template>

<script lang="ts" setup>
import { ref ,computed, onMounted} from 'vue';
import request from '@/utils/request';
import Pagination from '../tool/Pagination.vue';
import { ElMessage, ElMessageBox } from 'element-plus'



const inputName= ref(null)  //查询输入的名字
const valueType = ref(null)
const dialogVisibleAdd = ref(false)
const currentPage = ref(1); // 当前页
const pageSize = ref(8); // 每页条数
const userName = ref();
const valueAddNew = ref()
const valueChange = ref()
const dialogVisibleChange = ref(false)
const userNameChange = ref();
const passwordChange = ref();
const passwordConfirm = ref();
const primaryUsername = ref();
const userId = ref()


const selectUserByCondition = () => {
    request.post('/user/selectUserByCondition',{
        roleID:valueType.value,
        username:inputName.value,
    }).then(res=>{
       if(res.data.status == "fail"){
        ElMessage.error(`查询失败，请检查网络后重试`)
       }else {
        ElMessage({
        message: '查询成功',
        type: 'success',
  })    
        // 映射接口数据，提取所需字段
      tableData.value = res.data.map((item:any) => ({
        id: item.user.id,
        username: item.user.username,
        roleName: item.role.roleName,
        scenarioID: item.role.scenarioID,
        password:item.user.password
      }));
  
       }
    });
}
const addAlgorithm = () => {
    dialogVisibleAdd.value = true
   
}
const deleteItem = (item:any) => {
    ElMessageBox.confirm(
    `确认删除用户：（${item.username}）么？`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
        request.post('/user/deleteUserByID',{
        id:item.id
    }).then(res=>{
       if(res.data.status == "fail"){
        ElMessage.error(`删除用户（${item.username}）失败，请重试`)
       }else {
        ElMessage({
        message: '删除用户成功',
        type: 'success',
  })
        getAllUser()
       }
    });
    })
    .catch(() => {
    })
}

const changeAlgorithm = (item:any) => {
    userNameChange.value = item.username
    valueChange.value = item.roleID
    passwordChange.value = item.password
    passwordConfirm.value = item.password
    dialogVisibleChange.value = true
    primaryUsername.value = item.userName
    userId.value = item.id
}
// 修改用户信息
const upLoadMessage1 = async() => {
  if (!userNameChange.value && !passwordChange.value && !passwordConfirm.value && !valueChange.value && passwordChange.value === passwordConfirm.value) {
    console.error('请假查是否存在必填项未填写');
    return;
  }
  try {
        request.post('/user/updateUser', {
        id:userId.value,
        primaryUsername:primaryUsername.value,
        username:userNameChange.value,
        password:passwordChange.value,
        roleID:valueChange.value,
    }, {
    }).then(res=>{
       if(res.data.status == "fail"){
        ElMessage.error(`修改错误，请检查网络后重试`)
       }else {
        ElMessage({
        message: '修改个人信息成功',
        type: 'success',
  })
        getAllUser()
       }
    });
    dialogVisibleChange.value = false; // 关闭弹窗
  } catch (error) {
    console.error('Upload failed:', error);
  }
}



// 新建用户逻辑

const upLoadMessage = async() => {
  if (!userName.value && !valueAddNew.value ) {
    console.error('请确认必填项是否输入');
    return;
  }
  try {
        request.post('/user/insertUser', {
        username:userName.value,
        roleID:valueAddNew.value,
    }, {
    }).then(res=>{
       if(res.data.status == "fail"){
        ElMessage.error(`错误,新增用户失败`)
       }else {
        ElMessage({
        message: '成功，新增用户成功',
        type: 'success',
  })
        getAllUser()
       }
    });
    dialogVisibleAdd.value = false; // 关闭弹窗
  } catch (error) {
    console.error('Upload failed:', error);
  }
}

const tableData1 = computed(() =>{
      const start = (currentPage.value - 1) * pageSize.value;
      const end = start + pageSize.value;
      return tableData.value.slice(start, end);
}
);

const totalItems = computed(() => tableData.value.length);

const tableData = ref([])
// 获取所有用户数据
const getAllUser = () => {
  request
    .get('/user/getAllUser')
    .then((res) => {
      // 映射接口数据，提取所需字段
      tableData.value = res.data.map((item:any) => ({
        id: item.user.id,
        username: item.user.username,
        roleName: item.role.roleName,
        scenarioID: item.role.scenarioID,
        password:item.user.password
      }));
    })
    .catch((error) => {
      console.error('获取用户数据失败:', error);
    });
};
const formattedOptions = ref<any>()
const getAllRole = () =>{
    request.get('/user/getAllRole').then((res)=>{
        formattedOptions.value = res.data.map((item:any)=>({
            label : item.roleName,
            value : item.id
        }))
    })
} 
onMounted(()=>{
    getAllUser()
    getAllRole()
})

</script>

<style  scoped>
.container {
    width: 100%;
    height: 100%;
}
.header {
    width: 100%;
    height: 14%;
}
.main {
    width: 100%;
    height: 76%;
}
.el-pagination {
  background-color: transparent !important; /* 移除背景颜色 */
  box-shadow: none !important;             /* 去掉可能的阴影 */
}
</style>